package com.chaitin.xray.form;

import com.chaitin.xray.utils.IOUtil;
import com.chaitin.xray.utils.StringUtil;
import com.intellij.uiDesigner.core.GridConstraints;
import com.intellij.uiDesigner.core.GridLayoutManager;
import org.yaml.snakeyaml.LoaderOptions;
import org.yaml.snakeyaml.Yaml;
import org.yaml.snakeyaml.constructor.SafeConstructor;

import javax.swing.*;
import java.awt.*;
import java.io.InputStream;
import java.io.StringWriter;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.HashMap;
import java.util.Map;

public class ReverseForm {
    public JPanel reversePanel;
    private JTextField dbPathText;
    private JTextField tokenText;
    private JButton exportButton;
    private JPanel thePanel;
    private JLabel dbPathLabel;
    private JLabel tokenLabel;
    private JLabel httpLabel;
    private JPanel httpPanel;
    private JTextField ipText;
    private JTextField portText;
    private JLabel ipLabel;
    private JLabel portLabel;
    private JLabel exportLabel;

    private static String stdConfig;
    private static HashMap<String, Object> stdConfigObj;
    private static String dbPath;
    private static String token;
    private static String ip;
    private static String port;

    private void initLang() {
        if (MainForm.LANG == MainForm.CHINESE) {
            dbPathLabel.setText("  数据库文件");
            exportLabel.setText("  导出config.yaml配置文件");
            exportButton.setText("导出");
        } else {
            dbPathLabel.setText("  db_file_path");
            exportLabel.setText("  export server config.yaml");
            exportButton.setText("export");
        }
    }

    @SuppressWarnings("unchecked")
    public ReverseForm() {
        initLang();
        InputStream stdIs = ReverseForm.class.getClassLoader().getResourceAsStream("config.yaml");
        if (stdIs != null) {
            stdConfig = IOUtil.readStringFromIs(stdIs);
        }
        Yaml yaml = new Yaml(new SafeConstructor(new LoaderOptions()));
        stdConfigObj = yaml.load(stdConfig);

        exportButton.addActionListener(e -> {
            dbPath = dbPathText.getText();
            token = tokenText.getText();
            ip = ipText.getText();
            port = portText.getText();

            for (Map.Entry<String, Object> entry : stdConfigObj.entrySet()) {
                if (entry.getKey().equals("reverse")) {
                    Map<String, Object> reverse = (Map<String, Object>) entry.getValue();
                    reverse.put("db_file_path", dbPath);
                    reverse.put("token", token);
                    Map<String, Object> httpObj = (Map<String, Object>) reverse.get("http");
                    httpObj.put("enabled", true);
                    httpObj.put("listen_ip", ip);
                    httpObj.put("listen_port", port);
                    Map<String, Object> client = (Map<String, Object>) reverse.get("client");
                    if (!StringUtil.notEmpty(MainForm.instance.httpReverseText.getText())) {
                        if (MainForm.LANG == MainForm.CHINESE) {
                            JOptionPane.showMessageDialog(this.reversePanel,
                                    "请先填写: 主界面->反连->http url");
                        } else {
                            JOptionPane.showMessageDialog(this.reversePanel,
                                    "Input main form -> reverse -> http url first");
                        }
                        return;
                    }
                    client.put("http_base_url", MainForm.instance.httpReverseText.getText());
                }
            }

            if (StringUtil.notEmpty(dbPath) && StringUtil.notEmpty(token) &&
                    StringUtil.notEmpty(ip) && StringUtil.notEmpty(port)) {
                StringWriter writer = new StringWriter();
                yaml.dump(stdConfigObj, writer);
                stdConfig = writer.toString();
            } else {
                JOptionPane.showMessageDialog(this.reversePanel, "error config");
                return;
            }
            Path targetPath = Paths.get("reverse/config.yaml");
            try {
                Files.createDirectory(Paths.get("reverse"));
            } catch (Exception ignored) {
            }
            try {
                Files.delete(targetPath);
            } catch (Exception ignored) {
            }
            try {
                Files.write(targetPath, stdConfig.getBytes());
            } catch (Exception ignored) {
            }
            JOptionPane.showMessageDialog(this.reversePanel, "write file to reverse/config.yaml");
        });
    }

    {
// GUI initializer generated by IntelliJ IDEA GUI Designer
// >>> IMPORTANT!! <<<
// DO NOT EDIT OR ADD ANY CODE HERE!
        $$$setupUI$$$();
    }

    /**
     * Method generated by IntelliJ IDEA GUI Designer
     * >>> IMPORTANT!! <<<
     * DO NOT edit this method OR call it in your code!
     *
     * @noinspection ALL
     */
    private void $$$setupUI$$$() {
        reversePanel = new JPanel();
        reversePanel.setLayout(new GridLayoutManager(2, 2, new Insets(0, 0, 0, 0), -1, -1));
        reversePanel.setBackground(new Color(-12828863));
        thePanel = new JPanel();
        thePanel.setLayout(new GridLayoutManager(3, 2, new Insets(0, 0, 0, 0), -1, -1));
        thePanel.setBackground(new Color(-12828863));
        reversePanel.add(thePanel, new GridConstraints(0, 0, 1, 2, GridConstraints.ANCHOR_CENTER, GridConstraints.FILL_BOTH, GridConstraints.SIZEPOLICY_CAN_SHRINK | GridConstraints.SIZEPOLICY_CAN_GROW, GridConstraints.SIZEPOLICY_CAN_SHRINK | GridConstraints.SIZEPOLICY_CAN_GROW, null, null, null, 0, false));
        dbPathText = new JTextField();
        thePanel.add(dbPathText, new GridConstraints(0, 1, 1, 1, GridConstraints.ANCHOR_WEST, GridConstraints.FILL_HORIZONTAL, GridConstraints.SIZEPOLICY_WANT_GROW, GridConstraints.SIZEPOLICY_FIXED, null, new Dimension(150, -1), null, 0, false));
        dbPathLabel = new JLabel();
        dbPathLabel.setText("  db_file_path");
        thePanel.add(dbPathLabel, new GridConstraints(0, 0, 1, 1, GridConstraints.ANCHOR_WEST, GridConstraints.FILL_NONE, GridConstraints.SIZEPOLICY_FIXED, GridConstraints.SIZEPOLICY_FIXED, null, null, null, 0, false));
        tokenLabel = new JLabel();
        tokenLabel.setText("  token");
        thePanel.add(tokenLabel, new GridConstraints(1, 0, 1, 1, GridConstraints.ANCHOR_WEST, GridConstraints.FILL_NONE, GridConstraints.SIZEPOLICY_FIXED, GridConstraints.SIZEPOLICY_FIXED, null, null, null, 0, false));
        tokenText = new JTextField();
        tokenText.setText("");
        thePanel.add(tokenText, new GridConstraints(1, 1, 1, 1, GridConstraints.ANCHOR_WEST, GridConstraints.FILL_HORIZONTAL, GridConstraints.SIZEPOLICY_WANT_GROW, GridConstraints.SIZEPOLICY_FIXED, null, new Dimension(150, -1), null, 0, false));
        httpLabel = new JLabel();
        httpLabel.setText("  http");
        thePanel.add(httpLabel, new GridConstraints(2, 0, 1, 1, GridConstraints.ANCHOR_WEST, GridConstraints.FILL_NONE, GridConstraints.SIZEPOLICY_FIXED, GridConstraints.SIZEPOLICY_FIXED, null, null, null, 0, false));
        httpPanel = new JPanel();
        httpPanel.setLayout(new GridLayoutManager(2, 2, new Insets(0, 0, 0, 0), -1, -1));
        httpPanel.setBackground(new Color(-12828863));
        thePanel.add(httpPanel, new GridConstraints(2, 1, 1, 1, GridConstraints.ANCHOR_CENTER, GridConstraints.FILL_BOTH, GridConstraints.SIZEPOLICY_CAN_SHRINK | GridConstraints.SIZEPOLICY_CAN_GROW, GridConstraints.SIZEPOLICY_CAN_SHRINK | GridConstraints.SIZEPOLICY_CAN_GROW, null, null, null, 0, false));
        ipText = new JTextField();
        ipText.setText("0.0.0.0");
        httpPanel.add(ipText, new GridConstraints(0, 1, 1, 1, GridConstraints.ANCHOR_WEST, GridConstraints.FILL_HORIZONTAL, GridConstraints.SIZEPOLICY_WANT_GROW, GridConstraints.SIZEPOLICY_FIXED, null, new Dimension(150, -1), null, 0, false));
        portText = new JTextField();
        httpPanel.add(portText, new GridConstraints(1, 1, 1, 1, GridConstraints.ANCHOR_WEST, GridConstraints.FILL_HORIZONTAL, GridConstraints.SIZEPOLICY_WANT_GROW, GridConstraints.SIZEPOLICY_FIXED, null, new Dimension(150, -1), null, 0, false));
        ipLabel = new JLabel();
        ipLabel.setText("IP");
        httpPanel.add(ipLabel, new GridConstraints(0, 0, 1, 1, GridConstraints.ANCHOR_WEST, GridConstraints.FILL_NONE, GridConstraints.SIZEPOLICY_FIXED, GridConstraints.SIZEPOLICY_FIXED, null, null, null, 0, false));
        portLabel = new JLabel();
        portLabel.setText("Port");
        httpPanel.add(portLabel, new GridConstraints(1, 0, 1, 1, GridConstraints.ANCHOR_WEST, GridConstraints.FILL_NONE, GridConstraints.SIZEPOLICY_FIXED, GridConstraints.SIZEPOLICY_FIXED, null, null, null, 0, false));
        exportLabel = new JLabel();
        exportLabel.setText("  export server config.yaml");
        reversePanel.add(exportLabel, new GridConstraints(1, 0, 1, 1, GridConstraints.ANCHOR_WEST, GridConstraints.FILL_NONE, GridConstraints.SIZEPOLICY_FIXED, GridConstraints.SIZEPOLICY_FIXED, null, null, null, 0, false));
        exportButton = new JButton();
        exportButton.setText("export");
        reversePanel.add(exportButton, new GridConstraints(1, 1, 1, 1, GridConstraints.ANCHOR_CENTER, GridConstraints.FILL_HORIZONTAL, GridConstraints.SIZEPOLICY_CAN_SHRINK | GridConstraints.SIZEPOLICY_CAN_GROW, GridConstraints.SIZEPOLICY_FIXED, null, null, null, 0, false));
    }

    /**
     * @noinspection ALL
     */
    public JComponent $$$getRootComponent$$$() {
        return reversePanel;
    }
}
